package com.atled.exceptions;

import java.io.IOException;
import java.io.OutputStream;

public class StandardExceptionHandler {

	private final boolean dieOnException;
	
	private final Class<?> customerClass;
	
	private final OutputStream stdOut;
	
	private final OutputStream errOut;
	
	public StandardExceptionHandler(Class<?> customerClass) {
		// TODO: change this to a config
		this(customerClass, true);
	}
	
	public StandardExceptionHandler(Class<?> customerClass, boolean dieOnException) {
		this(customerClass, dieOnException, System.out, System.err);
	}
	
	public StandardExceptionHandler(Class<?> customerClass, boolean dieOnException, OutputStream stdOut, OutputStream errOut) {
		this.customerClass = customerClass;
		this.dieOnException = dieOnException;
		this.stdOut = stdOut;
		this.errOut = errOut;
	}
	
	public void handle(Exception e) {
		try {
			if (dieOnException) {
				errOut.write(e.getStackTrace().toString().getBytes());
				System.exit(0);
			} else {
				String out = "!!exception!!\n" + e.getStackTrace().toString();
				stdOut.write(out.getBytes());
			}
		} catch (IOException e1) {
			// well shit...
		}
	}
}
